#include "stdafx.h"
#include "ScreenCapture.h"

#define PORT 2973
#define BASE_COUNT 100

void ScreenCapture::Create()
{
	_captureCount = 0;

	base::Screen scr;
	scr.GetScreen();
	scrW = scr.Width;
	scrH = scr.Height;

	base::Bitmap bmp;
	bmp.CreateCompatibleBitmap(scrW,scrH);
	_screenBmp.Create(bmp.Detach());

	_screenDC.GetDC(GetDesktopWindow());

	_refeshTimer.EventTimer.Bind(this,&ScreenCapture::_OnRefresh);
	_refeshTimer.Create(500);

	_server.EventAccept.Bind(this,&ScreenCapture::_OnAccept);
	if(!_server.Starup(PORT))
	{
		base::String msg;
		base::GetSystemMessage(msg,WSAGetLastError());
		::MessageBox(0,msg,L"Error",MB_ICONERROR);
		PostQuitMessage(0);
	}
}
void ScreenCapture::_OnAccept(SOCKET socket)
{
	TCPStream* sk = _andClient.Add();
	sk->Attach(socket,1);
}
void ScreenCapture::WaitClose()
{
	for(uint i=0;i<_andClient.Count();i++)
	{
		_andClient[i].Close();
		_andClient[i].WaitClose();
	}
}
void ScreenCapture::_OnRefresh(UINT,LPARAM)
{
	/*BLENDFUNCTION bf;
	bf.AlphaFormat = 0;
	bf.BlendFlags = 0;
	bf.BlendOp = 0;
	bf.SourceConstantAlpha = 255;
	int r = ::AlphaBlend(_screenBmp,0,0,scrW,scrH,_screenDC,0,0,scrW,scrH,bf);
	if(r==0) return;*/
	BitBlt(_screenBmp,0,0,scrW,scrH,_screenDC,0,0,SRCCOPY);
	int proto = ((_captureCount%100)==0);
	if(proto)
	{
		_captureCount = 0;
		if(_screenData.IsNull())
			_screenData.SetLength(scrH*scrW*4);
	}
	_captureCount++;

	base::Bitmap bmp;
	bmp.Attach(_screenBmp.GetBitmap());
	base::Memory<byte> pix,data;
	if(bmp.GetPixelData(&pix)==0) return;
	data.SetLength(scrH*scrW*4);

	uint* iPix = (uint*)pix.Handle();
	uint* iScr = (uint*)_screenData.Handle();
	uint* iData = (uint*)data.Handle();
	for(int i=0;i<scrH;i++)
	{
		for(int j=0;j<scrW;j++)
		{
			uint index = i*scrW + j;
			if(proto)
				iData[index] = iPix[index];
			else
				iData[index] = iPix[index] - iScr[index];
			iScr[index] = iPix[index];
		}
	}

	for(uint i=0;i<_andClient.Count();i++)
	{
		if(!_andClient[i].SendPack((const char*)data.Handle(),data.Length(),(char*)&proto,4))
		{
			_andClient.Delete(i);
			i--;
			continue;
		}
	}
}